//
//  MDHTableViewModel.m
//  JSTech
//
//  Created by 高得华 on 2019/4/27.
//  Copyright © 2020 华&梅. All rights reserved.
//

#import "MDHTableViewModel.h"

#if __has_include("MDHPT/MDHPT-Swift.h")
#import "MDHPT/MDHPT-Swift.h"
#else
#import "JSTech-Swift.h"
#endif

@interface MDHTableViewModel ()
/// request remote data cmd
@property (nonatomic, readwrite, strong) RACCommand *requestRemoteDataCommand;
@end


@implementation MDHTableViewModel
- (void)initialize {
    [super initialize];
    
    self.page = 1;
    self.perPage = 20;
    self.style = UITableViewStylePlain;
    self.pageModel = [MDHBaseNetMetaModel new];
    self.hiddenFooterNoMoreData = true;
    self.shouldEndRefreshingWithNoMoreData = true;
    
    /// request remote data
    @weakify(self)
    self.requestRemoteDataCommand = [[RACCommand alloc] initWithSignalBlock:^(NSNumber * isHeader) {
        @strongify(self)
        self.page = isHeader.boolValue ? 1:self.page+1;
        return [[self requestRemoteDataSignalWithPage:self.page] takeUntil:self.rac_willDeallocSignal];
    }];
    
    [[[self rac_valuesForKeyPath:@"pageModel" observer:self] deliverOnMainThread] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        self.perPage = self.pageModel.perPage;
    }];
    
    /// 过滤错误信息
    [[self.requestRemoteDataCommand.errors
      filter:[self requestRemoteDataErrorsFilter]]
     subscribe:self.errors];
}

/// sub class can ovrride it
- (BOOL (^)(NSError *error))requestRemoteDataErrorsFilter {
    return ^(NSError *error) {
        return YES;
    };
}

- (id)fetchLocalData {
    return nil;
}

- (NSUInteger)offsetForPage:(NSUInteger)page {
    return (page - 1) * self.perPage;
}


- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page {
    return [RACSignal empty];
}

@end
